package com.shuimin.group;

import pond.common.FILE;
import pond.common.S;
import pond.common.STRING;
import pond.web.Render;
import pond.web.Request;
import pond.web.Router;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class INNER_IMPORT extends Router {
    public static final String ASSETS_DIR =  "assets";//  /images/place/
    {
        post("/image_url", (req, resp) -> {
            Request.UploadFile uf = req.file("content");
            String dir =  req.param("dir");
            if (STRING.isBlank(dir) || (! new File(ASSETS_DIR+dir).isDirectory()))
            {
                resp.send(400,dir +" not existed" );
                return;
            }
            if (uf == null || STRING.isBlank(uf.filename()))
            {
                resp.send(400,"no file receive");
                return;
            }
            S.echo("name:"+ uf.filename());
            String file_name  = S.now()+ uf.filename() ;
            try {
                FILE.inputStreamToFile(uf.inputStream(), new File(ASSETS_DIR+ dir + file_name));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //todo 修改路由地址 www.
            String www_url = "http://www.wonderfeng.xin"+ dir;
            resp.status(200);
            resp.render(Render.text(www_url+ file_name));
        });
        post("/multi_images", (req, resp) -> {
            Map<String, List<Request.UploadFile>> map =  req.files();
            if (null == map || map.size() ==0)
            {
                resp.send(400, "files not existed" );
                return;
            }
            String dir =  req.param("dir");
            if (STRING.isBlank(dir) || (! new File(ASSETS_DIR+dir).isDirectory()))
            {
                resp.send(400,dir +" not existed" );
                return;
            }

            List<Request.UploadFile> images = new ArrayList<>();
            S._for(map).each(item->{
                images.addAll(item.getValue());
            });
            if (images == null || images.size() ==0)
            {
                resp.send(400,"no file receive");
                return;
            }
            Map<String,String> retMap = new HashMap<>();
            //todo 修改路由地址 www.
            String www_url = "http://www.wonderfeng.xin"+ dir;
            S._for(images).each(image->{
                String file_name  = image.filename() ;
                try {
                    FILE.inputStreamToFile(image.inputStream(), new File(ASSETS_DIR + dir + file_name));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                retMap.put(file_name, www_url + file_name);
            });
            resp.status(200);
            resp.render(Render.json(retMap));
        });

    }
}
